package com.android.waterdetection.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DbOpenHelper {
    private static String driver = "com.mysql.jdbc.Driver";// mysql 驱动
    private static String ip = "119.3.211.202";
    private static String dbName = "water";
    private static String url = "jdbc:mysql://" + ip + ":3306/" + dbName
            + "?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC";    // mysql 数据库连接 url
    private static String user = "root";     // 用户名
    private static String password = "lzc709394+0211"; // 密码

    /**
     * 连接数据库
     */
    public static Connection getConnection() {
        Connection sConnection = null;
        try {
            Class.forName(driver);  // 获取 mysql 驱动
            sConnection = DriverManager.getConnection(url, user, password);   // 获取连接
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return sConnection;
    }

    /**
     * 关闭数据库
     */
    public static void closeConnection(Connection connection, PreparedStatement ps) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭数据库
     */
    public static void closeConnection(Connection connection, PreparedStatement ps, ResultSet resultSet) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}